<?php
/**
 * This file is part of the Agora distribution. 
 * Detailed copyright and licensing information can be found
 * in the gpl-3.0.txt file which should be included in the distribution.
 * 
 * @version		$Id: 3.0.14 Olympus 2010-09-28 rammstein4o $
 * @copyright  2007 - 2010 jVitals
 * @license   GPLv3 Open Source
 * @link       http://jvitals.com
 * @since      File available since initial release
 */
defined ('IN_AGORA') or die;

class TopicModel extends Model
{
    function __construct()
    {
        parent::__construct('topics');
    }

	// there is similar function in forums model. Don't mess them
	// this one users posts array as input
	function loadSubjectsMess($post_ids)
	{
		if (!is_array($post_ids) || empty($post_ids)) return array();
		$this->db->bindList('ids',$post_ids,'integer');
		$this->db->setQuery('SELECT DISTINCT forum.id as forum_id, topic.id as topic_id, topic.num_replies, forum.cat_id, topic.subject, post.message, topic.sticky, topic.closed'.
					' FROM ##__topics AS topic'.
					' INNER JOIN ##__posts AS post'.
					'  ON post.topic_id = topic.id'.
					' INNER JOIN ##__forums AS forum'.
					'  ON forum.last_post_id = post.id'.
					' WHERE post.id IN (:ids)');
		return $this->db->loadAssocList('forum_id');
	}

    function move($source_topic, $dest_forum)
    {
        $dest_forum = intval($dest_forum);
        $source_topic = intval($source_topic);

        $source_forum = $this->getForumId($source_topic);

        $this->db->setQuery('SELECT num_replies FROM ##__topics WHERE id='.$source_topic);
        $num_replies = $this->db->loadResult();

        $this->db->setQuery('UPDATE ##__forums SET num_topics=num_topics-1, num_posts=num_posts-'.$num_replies.' WHERE id='.$source_forum);
        $this->db->query();

        $this->db->setQuery('UPDATE ##__forums SET num_topics=num_topics+1, num_posts=num_posts+'.$num_replies.' WHERE id='.$dest_forum);
        $this->db->query();

        $this->db->setQuery('UPDATE ##__topics SET forum_id='.$dest_forum.' WHERE id='.$source_topic);
        $this->db->query();

        $this->fixLastPost($source_forum);
        $this->fixLastPost($dest_forum);
    }

    function merge($source_topic, $dest_topic)
    {
        $dest_topic = intval($dest_topic);
        $source_topic = intval($source_topic);

        $source_forum = $this->getForumId($source_topic);
        $dest_forum = $this->getForumId($dest_topic);

        $this->db->setQuery('SELECT num_replies FROM ##__topics WHERE id='.$source_topic);
        $num_replies = $this->db->loadResult();

        $this->db->setQuery('UPDATE ##__forums SET num_topics=num_topics-1, num_posts=num_posts-'.$num_replies.' WHERE id='.$source_forum);
        $this->db->query();

        $this->db->setQuery('UPDATE ##__forums SET num_posts=num_posts+'.($num_replies+1).' WHERE id='.$dest_forum);
        $this->db->query();

        $this->db->setQuery('UPDATE ##__topics SET num_replies=num_replies+'.($num_replies+1).' WHERE id='.$dest_topic);
        $this->db->query();

        $this->db->setQuery('UPDATE ##__posts SET posted = '.AGORA_TIME.', topic_id='.$dest_topic.' WHERE topic_id='.$source_topic);
        $this->db->query();

        $this->db->setQuery('DELETE FROM ##__topics WHERE id='.$source_topic);
        $this->db->query();

        $this->fixLastPost($source_forum);
        $this->fixLastPost($dest_forum);
    }

    function getForumId($topic_id)
    {
        $this->db->setQuery('SELECT forum_id FROM ##__topics WHERE id = '.intval($topic_id));
        return $this->db->loadResult();
    }

    function loadAllCount($allowed_forums) {
	
		$wherearr = array();
		$where = '';
		
		$wherearr[] = 'approved = 1';
        if ($allowed_forums) {
            $this->db->bindList('forums',$allowed_forums,'integer');
            $wherearr[] = 'forum_id IN (:forums)';
        }
		if (count($wherearr)) $where = 'WHERE ' . implode(' AND ', $wherearr);
		
		$sql = 'SELECT COUNT(*) FROM ##__topics ' . $where;
		$this->db->setQuery($sql);
        return $this->db->loadResult();
    }
	
    function loadAll($key = '', $per_page = null, $page = null, $allowed_forums =array()) {
	
		$wherearr = array();
		$where = '';
		
        if (is_null($per_page) || is_null($page)) {
            $limit = '';
        } else {
            $limit = Model::getLimit($per_page, $page);
        }
		
		$wherearr[] = 't.approved = 1';
        if ($allowed_forums) {
            $this->db->bindList('forums',$allowed_forums,'integer');
            $wherearr[] = 't.forum_id IN (:forums)';
        }
		if (count($wherearr)) $where = 'WHERE ' . implode(' AND ', $wherearr);
		
        $this->db->setQuery('SELECT t.*, p.message as postcontent, f.forum_type as forum_type FROM ##__topics t ' //joopport modified  добавил "f.forum_type as forum_type"
							. ' LEFT JOIN ##__posts AS p ON t.last_post_id = p.id AND t.last_post_id <> 0 '
							. ' LEFT JOIN ##__forums AS f ON t.forum_id = f.id ' //joopport added
							. $where 
							. ' ' . $this->order 
							. ' ' . $limit);	
        $result = $this->db->loadAssocList($key);
        return $result;
    }

    function loadAllCountByCat($cat_id, $allowed_forums) {
		$this->db->bindList('catid',$cat_id,'integer');
		$where = ' WHERE f.cat_id = :catid ';
        if ($allowed_forums) {
            $this->db->bindList('forums',$allowed_forums,'integer');
            $where = ' AND f.id IN (:forums) ';
        }
		$where .= ' AND t.approved = 1 ';
        $this->db->setQuery('SELECT COUNT(t.id) FROM ##__topics AS t JOIN ##__forums AS f ON t.forum_id = f.id ' . $where);
        return $this->db->loadResult();
    }

    function loadAllByCat($cat_id, $key = '', $per_page = null, $page = null, $allowed_forums = array()) { 
        if (is_null($per_page) || is_null($page)) {
            $limit = '';
        } else {
            $limit = Model::getLimit($per_page, $page);
        }

		$this->db->bindList('catid',$cat_id,'integer');
		$where = ' WHERE f.cat_id = :catid ';

        if ($allowed_forums) {
            $this->db->bindList('forums',$allowed_forums,'integer');
            $where .= ' AND f.id IN (:forums) ';
        }
		
		$where .= ' AND t.approved = 1 ';
		
        $this->db->setQuery('SELECT t.*, p.message as postcontent FROM ##__topics t, f.forum_type as forum_type ' //joopport modified  добавил "f.forum_type as forum_type"
							. ' JOIN ##__forums AS f ON t.forum_id = f.id '
							. ' LEFT JOIN ##__posts AS p ON t.last_post_id = p.id AND t.last_post_id <> 0 '
							. $where 
							. ' ' . $this->order 
							. ' ' . $limit);	
        $result = $this->db->loadAssocList($key);
        return $result;
    }


    function loadPosts($top_id, $per_page, $page, $reverse, $total_posts, $post_id = null) {
	
        $limit = Model::getLimit($per_page,$page);
        $config = & Model::getInstance('ConfigModel');
        $agora_config = $config->load();

        $sort = '';
        if ($reverse) {
            $sort = "DESC";
        } else {
            $sort = "ASC";
        }
        
        if ($post_id) {
			$where_and = ' AND id > ' . $this->db->Quote($post_id);
        } else {
			$where_and = '';
		}
		
        $where_and .= ' AND approved = 1 ';
		
        $this->db->setQuery('SELECT * FROM ##__posts ' .
                    'WHERE topic_id = ' . $this->db->Quote($top_id) . $where_and . ' ' .
                    'ORDER BY posted ' . $sort . ', id ' . $sort . ' ' . $limit);
        $posts = $this->db->loadAssocList();

        $user = & Model::getInstance('UserModel');
        if ($reverse) {
            $num = $total_posts;
        } else {
            $num = 1;
        }
        $post = null;
        $key = null;

		$users = array();
        foreach ($posts as $key => $post) {
            if ($reverse) {
                $posts[$key]['post_number'] = $num-- - ($page - 1) * $per_page;
            } else {
                $posts[$key]['post_number'] = ($page - 1) * $per_page + $num++;
            }

			if (!$post['poster_id']) {
				$posts[$key]['num_pips'] = 1;
				$posts[$key]['user'] = $user->loadGuest($post['poster'], $post['poster_email']);
				$posts[$key]['user']['birthday'] = 'Never';
				continue;
			}
			if ($post['poster'] && !in_array($post['poster'], $users)) {
				$users[] = $post['poster'];
			}
			if ($post['edited_by'] && !in_array($post['edited_by'], $users)) {
				$users[] = $post['edited_by'];
			}
		}
		
		$users = $user->load($users, 'username');
		$ban_model = & Model::getInstance('BanModel');
		
		$has_aup = $user->hasAUP();
		$points = array();
		
		$aupusers = array();
		foreach ($users as $name => $usr) {
			$users[$name]['bannd'] = $ban_model->isBanned($usr['username']);
			if($has_aup) $aupusers[] = $usr['jos_id'];
		}
		if($has_aup && is_array($aupusers) && count($aupusers)>0) $points = $user->getAUPoints($aupusers);
		
		// get event dispatcher so we can add data from plugins
		$dispatcher =& JDispatcher::getInstance();
		JPluginHelper::importPlugin('agora');
		$viewer = $user->loadCurrent();
		
        foreach ($posts as $key => $post) {
			//if ($post['poster_id'] == 0) continue;

			if ($post['poster_id'] == 0 || !isset($users[$post['poster']])) {
				$posts[$key]['user'] = $user->loadGuest($post['poster'], $post['poster_email']);
				$posts[$key]['user']['birthday'] = 'Never';
			} else {
	            $posts[$key]['user'] = $users[$post['poster']];
		        $posts[$key]['user']['birthday'] = $posts[$key]['user']['birthday'] == 0 ? 0 : date($agora_config['o_date_format'], $posts[$key]['user']['birthday']);
				$posts[$key]['user']['birthday'] = Model::formatDate($posts[$key]['user']['birthday']);
				if ($post['edited_by']) $posts[$key]['user']['edited_by_name'] = $users[$post['edited_by']]['name'];
				$posts[$key]['user']['has_aup'] = $has_aup;
				if($has_aup && array_key_exists($users[$post['poster']]['jos_id'], $points)) {
					$posts[$key]['user']['points'] = $points[$users[$post['poster']]['jos_id']]['points'];
				}
				
			}
				
					// dispatch plugin event
					$extra = $dispatcher->trigger('onUserPostInfo', array(&$posts[$key], &$viewer));
					
					if (is_array($extra)) {
						$extra = implode('', $extra);
					} else {
						$extra = (string) $extra;
					}
					$posts[$key]['user']['extra'] = $extra;
        }
		
        return $posts;
    }

    function isSubscribed($topic_id, $user_id) {
        $this->db->bind('topic_id',$topic_id,'integer');
        $this->db->bind('user_id',$user_id,'integer');

        $this->db->setQuery('SELECT COUNT(*) FROM ##__subscriptions WHERE user_id=:user_id AND topic_id=:topic_id');
        return $this->db->loadResult();

    }

    function markForumRead($user_id, $forum_id, $timeout) {
        if ($user_id == 0) return;
        $this->db->bind('user_id', (int)$user_id, 'integer', true);
        $this->db->bind('forum_id', (int)$forum_id, 'integer');
        $this->db->bind('timeout', AGORA_TIME - $timeout, 'integer');
        $this->db->bind('time', AGORA_TIME, 'integer', true);
		
        $this->db->setQuery('SELECT topic.id'.
                    ' FROM ##__topics AS topic'.
                    ' WHERE topic.forum_id = :forum_id');
        $topics = $this->db->loadResultArray();

        $this->db->bindList('topics',$topics,'integer', true);
		
		/*
        $this->db->setQuery('SELECT topic.id'.
                    ' FROM ##__topics AS topic'.
                    ' WHERE topic.forum_id = :forum_id'.
                    ' AND topic.last_post > :timeout OR topic.last_post IS NULL');

        $topics = $this->db->loadResultArray();

        $this->db->bindList('topics',$topics,'integer');
        $this->db->setQuery('DELETE FROM ##__read_posts WHERE user_id=:user_id AND topic_id IN (:topics)');
        $this->db->query();
		
        foreach ($topics as $topic_id) {
            $this->db->bind('user_id',$user_id,'integer');
            $this->db->bind('topic_id',$topic_id,'integer');
            $this->db->setQuery('INSERT INTO ##__read_posts'.
                            ' (read_time, user_id, topic_id)'.
                            ' VALUES (:time, :user_id, :topic_id)');

            $this->db->query();
        }
		*/
		
		// update existing topics with newer activity as read
		$sql = 'UPDATE ##__read_posts SET read_time = :time WHERE user_id = :user_id AND topic_id IN (:topics) ';
		$this->db->setQuery($sql);
		$this->db->query();

		// insert new topics
		$sql = 'INSERT INTO ##__read_posts (read_time, user_id, topic_id) ' .
			' SELECT :time, :user_id, t.id ' .
			' FROM ##__topics AS t ' .
			' LEFT JOIN ##__read_posts AS r ON t.id = r.topic_id AND r.user_id = :user_id ' . 
			' WHERE t.id IN (:topics) AND r.id IS NULL ';
		$this->db->setQuery($sql);
		$this->db->query();
		
        $this->db->clear();
    }

    function markAllRead($user_id, $timeout) {
	
        if ($user_id == 0) return;
		
        $this->db->bind('user_id', (int)$user_id, 'integer', true);
        $this->db->bind('time', AGORA_TIME, 'integer', true);
		
		/*
        $this->db->setQuery('DELETE FROM ##__read_posts WHERE user_id=:user_id');
        $this->db->query();
		
        $this->db->bind('timeout',AGORA_TIME - $timeout,'integer');
		
        $this->db->setQuery('SELECT id FROM ##__topics'.
                                ' WHERE last_post > :timeout');
		
        $unread = $this->db->loadResultArray();
		
        foreach ($unread as $topic_id) {
            $this->db->bind('topic_id',$topic_id,'integer');
            $this->db->setQuery('INSERT INTO ##__read_posts'.
                            ' (read_time, user_id, topic_id)'.
                            ' VALUES (:time, :user_id, :topic_id)');

            $this->db->query();
        }
		*/
		
		// update existing topics with newer activity as read
		$sql = 'UPDATE ##__read_posts SET read_time = :time WHERE user_id = :user_id ';
		$this->db->setQuery($sql);
		$this->db->query();
		
		// insert new topics
		$sql = 'INSERT INTO ##__read_posts (read_time, user_id, topic_id) ' .
			' SELECT :time, :user_id, t.id ' .
			' FROM ##__topics AS t ' .
			' LEFT JOIN ##__read_posts AS r ON t.id = r.topic_id AND r.user_id = :user_id ' . 
			' WHERE r.id IS NULL ';
		$this->db->setQuery($sql);
		$this->db->query();
		
        // clear permanent binds
        $this->db->clear();
    }

    function markRead($topic_id, $user_id) {
        if ($user_id == 0) return;
        $this->db->bind('user_id',$user_id,'integer',true);
        $this->db->bind('topic_id',$topic_id,'integer',true);

        $this->db->setQuery('DELETE FROM ##__read_posts'.
                    ' WHERE user_id = :user_id AND topic_id = :topic_id');
        $this->db->query();

        $this->db->bind('time',AGORA_TIME,'integer',true);

        $this->db->setQuery('INSERT INTO ##__read_posts'.
                        ' (read_time, user_id, topic_id)'.
                        ' VALUES (:time, :user_id, :topic_id)');

        $this->db->query();

        $this->db->clear();
    }

    function addView($topic_id, $user_id)
    {
        $q_topic_id = $this->db->Quote($topic_id);

        $this->db->setQuery("UPDATE {$this->table} SET num_views = num_views + 1 WHERE id = $q_topic_id");

        if (!$this->db->query()) {
            print $this->db->getErrorMsg();
            die;
        }

        $this->markRead($topic_id, $user_id);
    }

	function addPost($topic_id, $forum_id, $message, $user_id, $username, $hide_smilies, $approved, $email = false) {
		
		// permanently bind common variables (will be used in more then 1 query)
		$this->db->bind('topic_id',$topic_id,'integer',true);
		$this->db->bind('user_name',$username,'string',true);
		$this->db->bind('user_id',$user_id,'integer',true);
		$this->db->bind('timestamp',AGORA_TIME,'integer',true);
		$this->db->bind('approved',$approved,'integer', true);

		// bind variables just for one query
		$this->db->bind('guest_email',$email,empty($email)?'null':'string');
		$this->db->bind('message',$message,'string');
		$this->db->bind('hide_smilies',$hide_smilies,'integer');

		$id = $this->db->Quote($topic_id);
		$message = $this->db->Quote($message);
		$q_user_id = $this->db->Quote($user_id);
		$user_name = $this->db->Quote($username);
		$hide_smilies = $this->db->Quote($hide_smilies);

		$this->db->setQuery('INSERT INTO ##__posts (message, poster_id, poster, poster_email, hide_smilies, posted, topic_id, approved) ' .
							'VALUES (:message, :user_id, :user_name, :guest_email, :hide_smilies, :timestamp, :topic_id, :approved)', 0, 0, '');

		$this->db->query();
		$post_id = $this->db->insertid();

		$this->db->bind('post_id',$post_id,'integer',true);

		if ($approved) {
			$this->db->setQuery('UPDATE ##__topics SET ' .
									'last_post = :timestamp, ' .
									'last_post_id = :post_id, ' .
									'last_poster = :user_name, ' .
									'num_replies = num_replies+1 ' .
								'WHERE id = :topic_id');
			$this->db->query();

			$this->db->bind('forum_id',$forum_id,'integer');

			$this->db->setQuery('UPDATE ##__forums SET ' .
									'last_post = :timestamp, ' .
									'last_post_id = :post_id, ' .
									'last_poster = :user_name, ' .
									'num_posts = num_posts+1 ' .
								'WHERE id = :forum_id');
			$this->db->query();
			
			$this->db->setQuery('UPDATE ##__users SET ' .
									'num_posts = num_posts+1, ' .
									'last_post = :timestamp ' .
								'WHERE id = :user_id');
			$this->db->query();
		}
		
		$this->db->setQuery('DELETE FROM ##__read_posts WHERE user_id <> :user_id AND topic_id = :topic_id');
		$this->db->query();

		// clear permanent bindings
		$this->db->clear();
		$this->markRead($topic_id, $user_id);

		return $post_id;
	}

    function edit($topic_id, $subject, $desc, $icon) {
        // we use this somewhere in backend
        if (is_array($subject)) {
            return parent::edit($topic_id, $subject);
        }

        $q_id = "'".intval($topic_id)."'";
        $q_subject = $this->db->Quote($subject);
        $q_desc = $this->db->Quote($desc);
        $icon = $this->db->Quote($icon);

        $this->setQuery("UPDATE ##__topics SET subject=$q_subject, descrip_t=$q_desc, icon_topic=$icon
                            WHERE id = $q_id");
        $this->db->query();
    }

	function add($forum_id, $subject, $desc, $icon, $user_name, $user_id, $message, $hide_smilies, $approved, $email = false) {
        
		$this->db->bind('forum_id',$forum_id,'integer',true);
		$this->db->bind('user_id',$user_id,'integer',true);
		$this->db->bind('user_name',$user_name,'string',true);
		$this->db->bind('timestamp',AGORA_TIME,'integer',true);
		$this->db->bind('approved',$approved,'integer', true);

		$this->db->bind('subject',$subject,'string');
		$this->db->bind('desc',$desc,'string');
		$this->db->bind('icon',$icon,'string');

		$this->db->setQuery('INSERT INTO ##__topics (subject,descrip_t, posted, forum_id, icon_topic, poster, approved) ' .
							'VALUES (:subject, :desc, :timestamp, :forum_id, :icon, :user_name, :approved)');
		$this->db->query();

		$topic_id = $this->db->insertid();
		
		$this->db->bind('topic_id',$topic_id,'integer', true);
		$this->db->bind('hide_smilies',$hide_smilies,'integer');
		$this->db->bind('message',$message,'string');
		$this->db->bind('guest_email',$email,empty($email)?'null':'string');

		$this->db->setQuery('INSERT INTO ##__posts (message, poster_id, poster, poster_email, hide_smilies, posted, topic_id, approved) ' .
							'VALUES (:message, :user_id, :user_name, :guest_email, :hide_smilies, :timestamp, :topic_id, :approved)');
		$this->db->query();

		$post_id = $this->db->insertid();

		$this->db->bind('post_id',$post_id,'integer', true);
		
		$this->db->setQuery('UPDATE ##__topics SET ' .
								'last_post = :timestamp, ' .
								'last_post_id = :post_id, ' .
								'last_poster = :user_name, ' .
								'num_replies = 0 ' .
							'WHERE id=:topic_id');
		$this->db->query();

		if ($approved) {
			
			JPluginHelper::importPlugin( 'agora', 'agoraautoarticle');
			$plugin =& JPluginHelper::getPlugin('agora', 'agoraautoarticle');
			$plugin_params = (is_object($plugin) && property_exists($plugin, 'params')) ? $plugin->params : null;
			$pluginParams = new JParameter( $plugin_params );
			if ($pluginParams->get('plg_mode', '')) {
				$dispatcher =& JDispatcher::getInstance();
				$params = array($forum_id, $topic_id, $subject, $desc, $message, $user_name );
				$dispatcher->trigger( 'onAutoArticle', $params);
			}
		
			$this->db->setQuery('UPDATE ##__forums SET ' .
									'last_post = :timestamp, ' .
									'last_post_id = :post_id, ' .
									'last_poster = :user_name, ' .
									'num_topics = num_topics+1 ' .
								'WHERE id=:forum_id');
			$this->db->query();
		
			$this->db->setQuery('UPDATE ##__users SET ' .
									'num_posts = num_posts+1, ' .
									'last_post = :timestamp ' .
								'WHERE id = :user_id');
			$this->db->query();
		}
		
		$this->db->clear();

		return $topic_id;

	}

    function addPoll($forum_id, $subject,$desc,$icon, $user_name, $question, $approved, $yes = null, $no = null) {
	
        $subject = $this->db->Quote($subject);
        $desc = $this->db->Quote($desc);
        $icon = $this->db->Quote($icon);
        $q_forum_id = $this->db->Quote($forum_id);
        $q_user_name = $this->db->Quote($user_name);
        $q_question = $this->db->Quote($question);
        $q_approved = $this->db->Quote($approved);

        $yes_no_fields = '';
        $yes_no_values = '';

        if ($yes !== NULL && $no !== NULL) {
            $yes_no_fields = ', yes, no';
            $yes_no_values = ', '.$this->db->Quote($yes). ", ". $this->db->Quote($no);
        }

        $this->db->setQuery("INSERT INTO {$this->table}".
                     " (subject,descrip_t, posted, forum_id, icon_topic, poster, approved, question $yes_no_fields)".
                     " VALUES ($subject, $desc, UNIX_TIMESTAMP(NOW()), $q_forum_id, $icon, $q_user_name, $q_approved, $q_question $yes_no_values)"
        );

        if (!$this->db->query()) {
            print $this->db->getErrorMsg();
            die;
        } else {
			$insertid = $this->db->insertid();
			$this->db->bind('forum_id',$forum_id,'integer',true);
			if ($approved) {
				$this->db->setQuery('UPDATE ##__forums SET'.
							' num_topics = num_topics+1'.
							' WHERE id=:forum_id');
				$this->db->query();
			}
            return $insertid;
        }
    }

    function fixLastPost($forum_id)
    {
        $this->db->bind('forum_id',$forum_id,'integer', true);

        $this->db->setQuery('SELECT post.id AS post_id, post.poster AS poster, post.posted AS post_time'.
                        ' FROM ##__posts AS post'.
                        '  INNER JOIN ##__topics AS topic'.
                        ' ON post.topic_id = topic.id'.
                        ' WHERE topic.forum_id=:forum_id'.
                        ' ORDER BY post.posted DESC LIMIT 1');

        list($last_post_id, $last_poster, $last_post) = $this->db->loadRow();

        if ($last_post_id) {
            $this->db->bind('last_post_id',$last_post_id,'integer');
            $this->db->bind('last_poster',$last_poster,'string');
            $this->db->bind('last_post',$last_post,'integer');
        } else {
            $this->db->bind('last_post_id','NULL','string');
            $this->db->bind('last_poster','NULL','string');
            $this->db->bind('last_post','NULL','string');
        }

        $this->db->setQuery('UPDATE ##__forums SET last_post=:last_post, last_poster=:last_poster, last_post_id=:last_post_id WHERE id=:forum_id');
        $this->db->query();

        $this->db->clear();
    }

    function delete($id)
    {
        $this->db->bind('topic_id',$id,'integer',true);
        $this->db->setQuery('SELECT forum_id, num_replies FROM ##__topics WHERE id=:topic_id LIMIT 1');
		$data = $this->db->loadAssoc();

        list($forum_id,$num_posts) = $this->db->loadRow();
		$num_posts = (int)$num_posts;
		if (!$forum_id) return;

        parent::delete($id);

        $this->db->setQuery('SELECT poster_id, COUNT(*) as count FROM ##__posts WHERE topic_id = :topic_id GROUP BY poster_id');
        $users = $this->db->loadAssocList();

		foreach ($users as $user) {
			$this->db->bind('count',$user['count'],'integer');
			$this->db->bind('user_id',$user['poster_id'],'integer');
			$this->db->setQuery('UPDATE ##__users SET num_posts = num_posts - :count WHERE id = :user_id');
			$this->db->query();
		}

        $this->db->setQuery('DELETE FROM ##__posts WHERE topic_id = :topic_id');
        $this->db->query();

        $this->db->setQuery('DELETE FROM ##__subscriptions WHERE topic_id = :topic_id');
        $this->db->query();

        $this->db->setQuery('DELETE FROM ##__read_posts WHERE topic_id = :topic_id');
        $this->db->query();

        $this->db->clear();

		$this->db->setQuery('UPDATE ##__forums SET ' .
							'num_topics = COALESCE((SELECT count(*) FROM ##__topics WHERE forum_id = ' . (int)$forum_id . '), 0), ' . 
							'num_posts = COALESCE((SELECT SUM(num_replies) FROM ##__topics WHERE forum_id = ' . (int)$forum_id . '), 0) ' .
							'WHERE id = ' . (int)$forum_id);
        //$this->db->setQuery('UPDATE ##__forums SET num_topics = num_topics - 1, num_posts = num_posts - '.$num_posts.' WHERE id='.intval($forum_id));

        $this->db->query();

        $this->fixLastPost($forum_id);
    }

    function cleanupRead($timeout)
    {
        $this->db->setQuery('DELETE FROM ##__read_posts WHERE read_time < '.intval($timeout));
        $this->db->query();
    }

    // $topics - array of topics
    // $user_id - current user id
    // returns topics from $topics that are read by user (not checking timout here)
    function filterRead($topics, $user_id)
    {
        if (intval($user_id) <= 0) return $topics;

        $this->db->bindList('topics',$topics,'integer');
        $this->db->bind('user_id',$user_id,'integer');

        $this->db->setQuery(
                'SELECT topic.id'.
                ' FROM ##__topics AS topic'.
                ' INNER JOIN ##__read_posts AS read_p'.
                '  ON topic.id = read_p.topic_id'.
                ' WHERE topic_id IN (:topics)'.
                '  AND read_p.user_id = :user_id'.
                '  AND read_p.read_time >= topic.last_post'
        );

        $read_topics = $this->db->loadResultArray();
        $result = array();

        foreach ($topics as $topic) {
            if (!in_array($topic, $read_topics)) {
                $result[] = $topic;
            }
        }

        return $result;
    }

    function hasNewPosts($topic_id, $user_id)
    {
		if (!$user_id) return false;
		
        $q_user_id = intval($user_id);
        $q_topic_id = intval($topic_id);

        $this->db->bind('topic_id',$topic_id,'integer');
        $this->db->bind('user_id',$user_id,'integer');
        $this->db->setQuery(
                'SELECT COUNT(*)'.
                ' FROM ##__topics AS topic'.
                ' INNER JOIN ##__read_posts AS read_p'.
                '  ON topic.id = read_p.topic_id'.
                ' WHERE topic_id = :topic_id'.
                '  AND read_p.user_id = :user_id'.
                '  AND read_p.read_time >= topic.last_post'
        );
/*SELECT read_p.*, topic.last_post
FROM jos_agora_topics AS topic
INNER JOIN jos_agora_read_posts AS read_p
 ON topic.id = read_p.topic_id
WHERE topic.id = 10
 AND
   read_p.user_id = 2
 AND
   read_p.read_time > topic.last_post*/

/*			$this->db->setQuery('SELECT COUNT(*) FROM'.
                " {$this->prefix}posts AS post ".
                " LEFT JOIN {$this->prefix}read_posts AS read_p".
                '  ON post.topic_id = read_p.topic_id'.
                " WHERE post.topic_id = $q_topic_id".
                "  AND (read_p.user_id IS NULL OR read_p.user_id = $q_user_id)".
                "  AND (read_p.read_time IS NULL OR read_p.read_time < post.posted) LIMIT 1");*/

        //echo $this->db->_sql;die;

        if ($this->db->loadResult() == 0) {
            //				die;
            return true;
        } else return false;
    }

    function getPostCount($topic_id)
    {
        $this->db->setQuery('SELECT COUNT(*) FROM ##__posts WHERE topic_id = '.intval($topic_id));
        return $this->db->loadResult();
    }

    function addRating($topic, $user, $rating)
    {
        $q_topic = $this->db->Quote($topic);
        $q_user = $this->db->Quote($user);
        $q_rating = $this->db->Quote($rating);

        $this->db->setQuery("INSERT INTO ##__ratings VALUES ($q_rating, $q_user, $q_topic)");
        $this->db->query();
    }

    function getRating($topic)
    {
        $this->db->setQuery('SELECT SUM(rate)/COUNT(rate)/2.0 FROM ##__ratings'.
                ' WHERE topic_id = '.intval($topic));

        return $this->db->loadResult();
    }

    function getRatings($topic)
    {
        $this->setQuery('SELECT r.rate / 2 as rate, j.username, u.id as user_id'.
                ' FROM ##__ratings AS r'.
                ' LEFT JOIN ##__users AS u'.
                '  ON r.user_id = u.id'.
                ' LEFT JOIN #__users AS j'.
                '  ON u.jos_id = j.id'.
                ' WHERE r.topic_id = '.intval($topic));

        return $this->db->loadAssocList();
    }

    function getPostMessage($post_id)
    {
        $this->db->setQuery('SELECT message FROM ##__posts WHERE id = '.intval($post_id));
        return $this->db->loadResult();
    }

}

?>
